package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: cl
 * @Date: 2022/5/2 - 05 - 02
 * @Description:
 */

/**
 * 拦截器设置类
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    /**
     * 请求到达之前(返回true：放行，返回false：拦截)
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1、获取请求头
        String token = request.getHeader("Authorization");

        //使用网关过滤器验证token

        //2、使用工具类，判断token是否有效(判断用户是否登录)
//        boolean re = JwtUtils.verifyToken(token);
//        //2.1token无效(用户未登录，返回给前端信息，设置状态码)
//        if (!re){
//
//            response.setStatus(401);
//            return false;
//        }
        //2.2token有效(用户已经登录放行，并把token数据解析放入线程中)

        //3、解析token
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String mobile = (String) claims.get("mobile");

        //封装对象放入线程
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);

        UserHolder.set(user);

        return true;
    }

    /**
     * 请求和响应结束以后(结束清空线程)
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
